import os
import traceback

from docx import Document
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.status import HTTP_500_INTERNAL_SERVER_ERROR

"""
    @url('/theory/')
"""


class TheoryViewSet(viewsets.ViewSet):

    def list(self, request):
        """

        @param request:
        @return:
        """
        file_dir = ".\\theory\\"
        try:
            params = self.request.query_params
            if params.get('name'):
                name = params.get('name') + ".docx"
                print(name)
                document = Document(file_dir + name)  # 打开文件demo.docx
                content_list = []
                for paragraph in document.paragraphs:
                    print(paragraph.text)  # 打印各段落内容文本
                    content_list.append({'content': paragraph.text})
                return Response(data=content_list)
            else:
                theory_list = []
                for root, dirs, files in os.walk(file_dir):
                    for name in files:
                        theory_list.append({'theoryName': str(name).split('.')[0]})

                return Response(data=theory_list)

        except Exception as e:
            traceback.print_exc()
        return Response(status=HTTP_500_INTERNAL_SERVER_ERROR)
